
local function extract_yaml_and_content(content)
    -- 查找 YAML Front Matter 的起始和结束位置
    local start_index, end_index = string.find(content, "---\n")
    if not start_index then
        return nil, content, "No YAML Front Matter found"
    end
    
    -- 提取 YAML Front Matter 的内容
    local yaml_content = string.sub(content, start_index + 4)
    end_index = string.find(yaml_content, "---\n")
    if not end_index then
        return nil, content, "Invalid YAML Front Matter format"
    end
    
    yaml_content = string.sub(yaml_content, 1, end_index - 1)

    -- 剩余的 Markdown 内容
    local remaining_content = string.sub(content, end_index + 8)

    -- 返回提取的 YAML 字符串和剩余的 Markdown 内容
    return yaml_content, remaining_content
end

local function processLinks(text)
    -- 初始化一个空表来保存找到的链接
    local links = {}
    
    -- 使用正则表达式来匹配链接格式并替换
    local output_str, _ = text:gsub("%[%[(.-)%]%]", function(match)
        local link_text = match
        local pipe_index = match:find("|")
        if pipe_index then
            -- 如果有 | 符号，则提取链接名称
            link_text = match:sub(pipe_index + 1, -1)
            match = match:sub(1, pipe_index - 1)
        end
        -- 将链接名称保存到表中
        links[#links + 1] = match
        -- 返回替换后的文本
        return string.format("[%s](%s)", link_text, match)
    end)

    return output_str , links
    
    -- 输出替换后的字符串
    -- print("替换后的字符串：", output_str)
    
    -- 输出保存的链接表
    -- print("保存的链接：")
    -- for i, v in ipairs(links) do
    --     print(i, v)
    -- end
end

-- { "xx":["x1","x2"], "yy":["y1","y2"] } -> [["xx","x1"],["xx","x2"],["yy","y1"],["yy","y2"]]
local function flattenLinks(uniqueLinks)
    local flatLinks = {}
    for key, values in pairs(uniqueLinks) do
        for _, value in ipairs(values) do
            table.insert(flatLinks, {key, value})
        end
    end
    return flatLinks
end

local function read(file)
    local file = io.open(file, "r")
    local content = file:read("*a")
    file:close()
    return content
end

-- 函数：读取 Markdown 文件并提取 #tag （未测试）
local function extractTags(filename)
    local tags = {}
    local file = io.open(filename, "r")
    if file then
        for line in file:lines() do
            local tagStart = line:find("#%s*")
            if tagStart then
                local tag = line:sub(tagStart + 1):gsub("%s+", "") -- 去除前后空格
                table.insert(tags, tag)
            end
        end
        file:close()
    end
    return tags
end

return {
    extract_yaml_and_content = extract_yaml_and_content,
    processLinks = processLinks,
    flattenLinks = flattenLinks,
    read = read,
    extractTags = extractTags
}